package com.chixing.ih.util;

import com.chixing.ih.status.ThumbsEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 目的:
 *
 * @author ：zcw
 * @version: 1.0  2020/9/22 21:00
 */
@Component
public class RedisPraiseUtil {
    private static String dataMap = "IT_LAUD";

    @Autowired
    private static RedisTemplate<String, Object> redisTemplate;

    public RedisPraiseUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * @description: 点赞或者取消赞
     * @param: String
     * @return: Boolean
     * @author: zcw
     * @date: 2020/9/21
     */
    public static Boolean redisSet(Long likedId, Long popularId) {
        String key = getLikedKey(likedId, popularId);
        Object map = redisTemplate.opsForHash().get(dataMap, key);
        if (null != map) {
            if ((int) map == 1) {
                redisTemplate.opsForHash().delete(dataMap, key);
                return false;
            }
        }
        try {
            redisTemplate.opsForHash().put(dataMap, key, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * @description: 获取key对应的状态
     * @param: String
     * @return: int
     * @author: zcw
     * @date: 2020/9/21
     */
    public static Integer redisGetState(Long likedId, Long popularId) {
        String key = getLikedKey(likedId, popularId);
        Object hget = redisTemplate.opsForHash().get(dataMap, key);
        if (null != hget) {
            return ThumbsEnum.ZERO.status;
        }
        return ThumbsEnum.ONE.status;
    }

    /**
     * @description: 获得点赞总数
     * @param: String 被点赞用户id
     * @return: long
     * @author: zcw
     * @date: 2020/9/22
     */
    public static Long redisGetTotal(Long userId) {
        Map<Object, Object> map = redisTemplate.opsForHash().entries(dataMap);
        long count = 0;
        Iterator<Map.Entry<Object, Object>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Object, Object> entry = iterator.next();
            String str = entry.getKey().toString();
            String pattern = "::" + userId + "$";
            Matcher matcher = Pattern.compile(pattern).matcher(str);
            if (matcher.find()) {
                count++;
            }
        }
        return count;
    }

    public static String getLikedKey(Long likedUserId, Long likedPostId) {
        StringBuilder builder = new StringBuilder();
        builder.append(likedUserId);
        builder.append("::");
        builder.append(likedPostId);
        return builder.toString();
    }


}
